package com.gs.synedocket.fragment.driver;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.synedocket.R;
import com.gs.synedocket.activity.ImagePreviewActivity;
import com.gs.synedocket.adapter.PhotoAdapter;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.control.TitleView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.CreateAddAcaDto;
import com.gs.synedocket.db.dto.DocketAdditionalDto;
import com.gs.synedocket.db.entity.DocketPhoto;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.ComboPicDialog;
import com.gs.synedocket.dialog.CommDialogUtils;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseFragment;
import com.gs.synedocket.presenter.DriverPlantPresenter;
import com.gs.synedocket.service.GpsService;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.DensityUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.FileUtils;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.PermissionUtil;
import com.gs.synedocket.util.PhotoUtil;
import com.gs.synedocket.util.StringUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.IDriverPlantView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class DriverPlantFragment extends BaseFragment<IDriverPlantView, DriverPlantPresenter> implements IDriverPlantView {

    private RadioGroup rgExtra;
    private RadioButton rbOther;
    private EditText etSlump, etTemperature, etExtraMileage, etOther, etComment;
    private PhotoAdapter adapter;
    private List<DocketPhoto> list;
    private AppCompatCheckBox cbTakeSample;
    private Integer type;
    private LinearLayout llPhoto;
    private CreateAddAcaDto mBean;
    private Button btnSubmit;
    private ImageView ivAddPhoto;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_driver_plant;
    }

    @Override

    protected DriverPlantPresenter createPresenter() {
        return new DriverPlantPresenter();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        MyOnClickListener onClickListener = new MyOnClickListener();
//        Additional information
        TitleView viewAdditional = fd(R.id.view_additional);
        viewAdditional.setContent(fd(R.id.ll_additional));
        etSlump = fd(R.id.et_slump);
        etTemperature = fd(R.id.et_temperature);
        etExtraMileage = fd(R.id.et_extra_mileage);
        cbTakeSample = fd(R.id.cb_take_sample);
        rbOther = fd(R.id.rb_other);
        rbOther.setOnCheckedChangeListener(new MyRBOnCheckedChangeListener());
        rgExtra = fd(R.id.rg_extra);
        rgExtra.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        etOther = fd(R.id.et_other);
//        Photo & Comment
        TitleView viewPhoto = fd(R.id.view_photo);
        llPhoto = fd(R.id.ll_photo);
        viewPhoto.setContent(llPhoto);
        etComment = fd(R.id.et_comment);
        list = new ArrayList<>();
        adapter = new PhotoAdapter(context, list, R.layout.rvitem_photo);
        adapter.setOnItemChildrenClickListener((v, position) -> {
            if (v.getId() == R.id.iv_delete) {
                deletePhoto(position);
            } else {
                Intent intent = new Intent();
                intent.setClass(context, ImagePreviewActivity.class);
                ArrayList<String> listPhotos = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    String photo = list.get(i).getPhoto();
                    listPhotos.add((StringUtil.isLocalPhoto(photo) ? "" : StringUtil.isNetPhoto(photo) ? "" : OKHttpUtil.IMG_URL) + photo);
                }
                intent.putExtra(AllConstants.WHAT, listPhotos);
                intent.putExtra(AllConstants.ID, position);
                startActivity(intent);
            }
        });
        RecyclerView rvPhoto = fd(R.id.rv_photo);
        rvPhoto.setLayoutManager(new GridLayoutManager(context, 3));
        rvPhoto.setAdapter(adapter);
        ivAddPhoto = fd(R.id.iv_add_photo);
        ivAddPhoto.setOnClickListener(onClickListener);
        btnSubmit = fd(R.id.btn_submit);
        btnSubmit.setOnClickListener(onClickListener);
    }

    @Override
    protected void initData() {
        setViewStatus();
        if (DocketUtil.getInstance().getAdditional() != null) {
            DocketAdditionalDto additional = DocketUtil.getInstance().getAdditional();
            etSlump.setText(additional.getSlump() == null ? "" : String.valueOf(additional.getSlump()));
            etTemperature.setText(additional.getTemperature() == null ? "" : String.valueOf(additional.getTemperature()));
            cbTakeSample.setChecked(additional.getTakeSample() == null ? false : additional.getTakeSample());
            etExtraMileage.setText(additional.getAddMileage() == null ? "" : String.valueOf(additional.getAddMileage()));
            if (additional.getAddType() != null) {
                type = additional.getAddType();
                if (type == 3) {
                    rbOther.setChecked(true);
                    etOther.setText(additional.getAddRemark());
                } else {
                    rgExtra.check(type == 1 ? R.id.rb_back_unloading : R.id.rb_transfer);
                }
            }
        }
        List<DocketPhoto> photos = DocketUtil.getInstance().getPhotos();
        if (photos != null && !photos.isEmpty()) {
            for (DocketPhoto bean : photos) {
                String photo = bean.getPhoto();
                list.add(new DocketPhoto((StringUtil.isLocalPhoto(photo) ? "" : OKHttpUtil.IMG_URL) + photo));
            }
            adapter.notifyDataSetChanged();
            setNewHeight(llPhoto, DensityUtil.displayViewHeight(llPhoto));
        }
        etComment.setText(DocketUtil.getInstance().getDriverRemark() == null ? "" : DocketUtil.getInstance().getDriverRemark());
    }

    private void setViewStatus() {
        boolean logDetail = DocketUtil.getInstance().isLogDetail();
        boolean enable = !logDetail;
        etSlump.setEnabled(enable);
        etTemperature.setEnabled(enable);
        cbTakeSample.setEnabled(enable);
        etExtraMileage.setEnabled(enable);
        for (int i = 0; i < rgExtra.getChildCount(); i++) {
            rgExtra.getChildAt(i).setEnabled(enable);
        }
        rbOther.setEnabled(enable);
        etOther.setEnabled(enable);
        etComment.setEnabled(enable);
        adapter.setLogDetail(logDetail);
        if (logDetail) {
            ivAddPhoto.setVisibility(View.GONE);
            btnSubmit.setBackgroundResource(R.drawable.gray_bg);
        } else {
            ivAddPhoto.setVisibility(View.VISIBLE);
            btnSubmit.setBackgroundResource(R.drawable.driver_rb_unchecked);
            setNewHeight(llPhoto, DensityUtil.displayViewHeight(llPhoto));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        int what = event.getWhat();
        if (what == EventCode.EVENT_DONE_ON_HAND || what == EventCode.EVENT_RESET) {
            refreshView();
            initData();
        }
    }

    private void refreshView() {
        etSlump.setText("");
        etTemperature.setText("");
        cbTakeSample.setChecked(false);
        etExtraMileage.setText("");
        rgExtra.clearCheck();
        etOther.setText("");
        type = null;
        etComment.setText("");
        int size = list.size();
        size = size % 3 == 0 ? size / 3 : (size / 3) + 1;
        setNewHeight(llPhoto, llPhoto.getHeight() - (DensityUtil.dp2px(110) * size));
        adapter.clear();
    }

    @Override
    public Double getSlump() {
        String s = etSlump.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Double getTemperature() {
        String s = etTemperature.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Boolean getTakeSample() {
        return cbTakeSample.isChecked();
    }

    @Override
    public Integer getAddMileage() {
        String s = etExtraMileage.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Integer getAddType() {
        return type;
    }

    @Override
    public String getAddRemark() {
        return etOther.getText().toString();
    }

    @Override
    public String getGps() {
        return GpsService.getGps();
    }

    @Override
    public String getGpsLoc() {
        return GpsService.getGpsLoc();
    }

    @Override
    public String getComment() {
        return etComment.getText().toString();
    }

    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            deletePhoto(list.size() - 1);
            return;
        }
        list.set(list.size() - 1, new DocketPhoto(apiResult.getData()));
    }

    @Override
    public void onUploadFileFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        deletePhoto(list.size() - 1);
    }

    private void deletePhoto(int position) {
        adapter.delete(position);
        int size = list.size();
        if (size % 3 == 0) {
            setNewHeight(llPhoto, llPhoto.getHeight() - DensityUtil.dp2px(110));
        }
    }

    private void setNewHeight(View v, int height) {
        ViewGroup.LayoutParams lp = v.getLayoutParams();
        lp.height = height;
        v.setLayoutParams(lp);
    }

    @Override
    public void onAddInfoSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            return;
        }
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.add_success);
        LogUtil.getInstance().insertOrReplaceData(DocketUtil.getInstance().getDocketNo() + "-添加附加信息成功");
        DBApi.getInstance().updateDocketUpload(mBean.getDocketId(), 0);
        DBApi.getInstance().insertAddAca(mBean);
        mBean = null;
    }

    @Override
    public void onAddInfoFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_submit) {
                if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                    ToastUtil.showToast(R.string.upgrade_first);
                    LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
                    return;
                }
                if (DocketUtil.getInstance().isLogDetail()) {
                    ToastDialogUtils.getInstance().showInfoMessage(context, R.string.docket_done);
                    return;
                }
                if (TextUtils.isEmpty(DocketUtil.getInstance().getDocketId())) {
                    ToastDialogUtils.getInstance().showInfoMessage(context, R.string.empty_docket);
                    return;
                }
//                    if (TextUtils.isEmpty(getGps())) {
//                        GpsUtil.getInstance().startLocation(getActivity());
//                        Toast.makeText(context, R.string.gps_empty, Toast.LENGTH_LONG).show();
//                        return;
//                    }
                mPresenter.addInfo(createDto());
            } else if (id == R.id.iv_add_photo) {
                CommDialogUtils.showComboPicDialog(getActivity(), "");
            }
        }
    }

    private CreateAddAcaDto createDto() {
        String docketId = DocketUtil.getInstance().getDocketId();
        mBean = new CreateAddAcaDto();
        if (!list.isEmpty()) {
            mBean.setPhotos(resetPhoto(list));
        }
        mBean.setDocketId(docketId);
        DocketAdditionalDto additionalDto = new DocketAdditionalDto();
        additionalDto.setDocketId(docketId);
        additionalDto.setSlump(getSlump());
        additionalDto.setTemperature(getTemperature());
        additionalDto.setTakeSample(getTakeSample());
        additionalDto.setAddMileage(getAddMileage());
        if (getAddType() != null) {
            additionalDto.setAddType(getAddType());
            if (getAddType() == 3) {
                additionalDto.setAddRemark(getAddRemark());
            }
        }
        additionalDto.setGps(getGps());
        additionalDto.setGpsLoc(getGpsLoc());
        mBean.setAdditional(additionalDto);
        mBean.setDriverRemark(getComment());
        return mBean;
    }

    private List<DocketPhoto> resetPhoto(List<DocketPhoto> list) {
        for (int i = 0; i < list.size(); i++) {
            String photo = list.get(i).getPhoto();
            if (photo.startsWith(OKHttpUtil.IMG_URL)) {
                list.get(i).setPhoto(photo.substring(OKHttpUtil.IMG_URL.length()));
            }
        }
        return list;
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (rbOther.isChecked()) {
                rbOther.setChecked(false);
            }
            if (checkedId == R.id.rb_back_unloading) {
                type = 1;
            } else {
                type = 2;
            }
        }
    }

    class MyRBOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            etOther.setEnabled(isChecked);
            if (isChecked) {
                type = 3;
                if (rgExtra.getCheckedRadioButtonId() != -1) {
                    rgExtra.setOnCheckedChangeListener(null);
                    rgExtra.clearCheck();
                    rgExtra.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PermissionUtil.requestPermission(grantResults)) {
            // 申请相机权限后返回
            if (requestCode == ComboPicDialog.PIC_CAMERA) {
                PhotoUtil.getInstance().toCamera(getActivity());
            }
            // 申请读取图库权限后返回
            else if (requestCode == ComboPicDialog.PIC_GALLERY) {
                PhotoUtil.getInstance().toGallery(getActivity());
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            String url = null;
            if (requestCode == AllConstants.PIC_CAMERA) {
                url = PhotoUtil.getInstance().handlePhoto(context);
            } else if (requestCode == AllConstants.PIC_GALLERY && data != null) {
                if (data.getData() != null) {
                    url = FileUtils.getFilePathByUri(context, data.getData());
                }
            }
            if (!TextUtils.isEmpty(url)) {
                adapter.add(new DocketPhoto(url));
                int size = list.size();
                if (size % 3 == 1) {
                    setNewHeight(llPhoto, llPhoto.getHeight() + DensityUtil.dp2px(110));
                }
                showLoading();
                mPresenter.upload(url);
            }
        }
    }
}
